package hikari.persistence;

import com.gooddies.wiring.Wiring;
import com.gooddies.wiring.WiringComponentHolder;
import com.gooddies.wiring.annotations.PostWiring;
import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.persistence.persisthandlers.IPersistantObject3dReadHandler;
import hikari.persistence.persisthandlers.PersistantHandler;
import hikari.utils.Utils;
import java.util.HashMap;

/**
 * @author Dmitry
 */
@WiringComponent(singleton = true)
@SuppressWarnings("unchecked")
public class PersistantHandlersSettings {

    private HashMap<String, IPersistantObject3dReadHandler> handlers = new HashMap<>();
    @Wire
    private Utils utils;
    //init basic read persistance handlers

    private PersistantHandlersSettings() {
    }

    @PostWiring
    private void init() {
        for (WiringComponentHolder holder : Wiring.get().getAllWiringComponents()) {
            if (holder.getClazz().isAnnotationPresent(PersistantHandler.class)) {
                PersistantHandler annotation = (PersistantHandler) holder.getClazz().getAnnotation(PersistantHandler.class);
                String sectionName = annotation.sectionName();
                IPersistantObject3dReadHandler handler = (IPersistantObject3dReadHandler) Wiring.getComponent(holder.getName());
                addPersistantHandler(sectionName, handler);
            }
        }
    }

    public final void addPersistantHandler(String sectionName, IPersistantObject3dReadHandler handler) {
        if (handlers.containsKey(sectionName)) {
            utils.logError("Error adding persistance handler to section "
                    + sectionName + " of the class ["
                    + handler.getClass().getName()
                    + "] because such section already defined.");
            return;
        }

        handlers.put(sectionName, handler);
    }

    public IPersistantObject3dReadHandler getHandler(String sectionName) {
        return handlers.get(sectionName);
    }
}
